import path = require('path');
import axios from 'axios';

import logger from './logger';
const fs = require('fs');

const Cache = (file: string) => {
	return /\.json$/.test(file) && fs.existsSync(file);
};

export async function readSchemaFromUrl (url: string): Promise<any> {
	try {
		url = decodeURIComponent(url);
		const web = encodeURI(url);
		const r = await axios.get(web);
		return r ? r.data : null;
	} catch (err) {
		logger.error(err);
		logger.error(url);
	}
}

export async function readSchemaFromFile (file: string): Promise<any> {
	return new Promise((resolve, reject) => {
		const cwd = process.cwd();
		try {
			const tmpl = path.resolve(cwd, file);
			if (Cache(tmpl)) {
				resolve(require(tmpl));
			} else {
				resolve(null);
				logger.error(tmpl.concat(' is not exist'));
			}
		} catch (error) {
			reject(error);
		}
	});
}
